package com.yuan.weike.service.impl;

import com.yuan.weike.exception.BusinessException;
import com.yuan.weike.exception.ErrorCode;
import com.yuan.weike.mapper.UserMapper;
import com.yuan.weike.model.User;
import com.yuan.weike.model.UserRoleEnum;
import com.yuan.weike.model.UserStatusEnum;
import com.yuan.weike.model.request.*;
import com.yuan.weike.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import cn.hutool.crypto.digest.DigestUtil;

import java.util.Date;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public long addUser(UserAddRequest userAddRequest, User loginUser) {
        // 检查参数
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户添加请求不能为空");
        }

        // 检查是否有权限添加用户（仅管理员可以添加用户）
        if (!isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限添加用户");
        }

        // 检查密码是否一致
        if (!userAddRequest.getPassword().equals(userAddRequest.getConfirmPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }

        // 检查用户名是否已存在
        User existUser = userMapper.selectByUsername(userAddRequest.getUsername());
        if (existUser != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
        }
        
        // 检查邮箱是否已存在
        existUser = userMapper.selectByEmail(userAddRequest.getEmail());
        if (existUser != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已存在");
        }

        // 创建用户
        User user = new User();
        user.setUsername(userAddRequest.getUsername());
        // 对密码进行加密处理
        user.setPassword(DigestUtil.md5Hex(userAddRequest.getPassword()));
        user.setEmail(userAddRequest.getEmail());
        user.setPhone(userAddRequest.getPhone());

        // 设置角色
        user.setRole(userAddRequest.getRole());

        user.setStatus(UserStatusEnum.NORMAL.getValue());
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());

        try {
            userMapper.insert(user);
        } catch (DuplicateKeyException e) {
            // 处理重复键异常，可能是用户名或邮箱重复
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或邮箱已存在");
        }
        return user.getUserId();
    }

    @Override
    public long userRegister(UserRegisterRequest userRegisterRequest) {
        // 检查参数
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户注册请求不能为空");
        }

        // 检查密码是否一致
        if (!userRegisterRequest.getPassword().equals(userRegisterRequest.getConfirmPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }

        // 检查用户名是否已存在
        User existUser = userMapper.selectByUsername(userRegisterRequest.getUsername());
        if (existUser != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
        }
        
        // 检查邮箱是否已存在
        existUser = userMapper.selectByEmail(userRegisterRequest.getEmail());
        if (existUser != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已存在");
        }

        // 创建用户
        User user = new User();
        user.setUsername(userRegisterRequest.getUsername());
        // 对密码进行加密处理
        user.setPassword(DigestUtil.md5Hex(userRegisterRequest.getPassword()));
        user.setEmail(userRegisterRequest.getEmail());
        user.setPhone(userRegisterRequest.getPhone());
        
        // 设置角色（默认为普通用户）
        user.setRole(UserRoleEnum.USER.getValue());
        
        user.setStatus(UserStatusEnum.NORMAL.getValue());
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());

        try {
            userMapper.insert(user);
        } catch (DuplicateKeyException e) {
            // 处理重复键异常，可能是用户名或邮箱重复
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名或邮箱已存在");
        }
        return user.getUserId();
    }

    @Override
    public User userLogin(UserLoginRequest userLoginRequest) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户登录请求不能为空");
        }

        // 查找用户
        User foundUser = userMapper.selectByUsername(userLoginRequest.getUsernameOrEmail());
        if (foundUser == null) {
            foundUser = userMapper.selectByEmail(userLoginRequest.getUsernameOrEmail());
        }

        // 验证用户是否存在以及密码是否正确
        if (foundUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        
        if (!foundUser.getPassword().equals(DigestUtil.md5Hex(userLoginRequest.getPassword()))) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }

        // 检查用户状态
        if (foundUser.getStatus() == UserStatusEnum.DISABLED.getValue()) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "用户已被禁用");
        }

        if (foundUser.getStatus() == UserStatusEnum.EMAIL_PENDING.getValue()) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "用户邮箱尚未验证");
        }

        // 更新最后登录时间
        foundUser.setLastLoginTime(new Date());
        // 更新数据库中的最后登录时间
        userMapper.updateUserInfo(foundUser);

        return foundUser;
    }

    @Override
    public User getCurrentUser(long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }
        return user;
    }

    @Override
    public boolean updateUserInfo(UserUpdateRequest userUpdateRequest, User loginUser) {
        if (userUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户更新请求不能为空");
        }

        // 检查是否有权限更新该用户信息（只能更新自己的信息，管理员除外）
        if (!loginUser.getUserId().equals(userUpdateRequest.getId()) && !isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限更新该用户信息");
        }

        // 查找要更新的用户
        User userToUpdate = userMapper.selectById(userUpdateRequest.getId());
        if (userToUpdate == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        // 更新用户信息
        userToUpdate.setUsername(userUpdateRequest.getUsername());
        userToUpdate.setEmail(userUpdateRequest.getEmail());
        userToUpdate.setPhone(userUpdateRequest.getPhone());
        userToUpdate.setAvatar(userUpdateRequest.getAvatar());
        
        // 更新角色（仅管理员可以修改角色）
        if (isAdmin(loginUser) && userUpdateRequest.getRole() != null) {
            userToUpdate.setRole(userUpdateRequest.getRole());
        }
        
        userToUpdate.setUpdatedTime(new Date());

        return userMapper.updateUserInfo(userToUpdate) > 0;
    }

    @Override
    public boolean resetPassword(UserResetPasswordRequest resetPasswordRequest) {
        if (resetPasswordRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "重置密码请求不能为空");
        }

        // 检查密码是否一致
        if (!resetPasswordRequest.getNewPassword().equals(resetPasswordRequest.getConfirmNewPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的新密码不一致");
        }

        // 查找用户
        User userToUpdate = userMapper.selectByEmail(resetPasswordRequest.getEmail());
        if (userToUpdate == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        // 实际项目中需要验证验证码
        // 这里简化处理，直接更新密码
        return userMapper.updatePassword(userToUpdate.getUserId(), DigestUtil.md5Hex(resetPasswordRequest.getNewPassword())) > 0;
    }

    @Override
    public List<User> listUsers(User loginUser) {
        // 检查是否为管理员
        if (!isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限查看用户列表");
        }

        return userMapper.selectAll();
    }

    @Override
    public boolean updateUserStatus(long userId, int status, User loginUser) {
        // 检查是否为管理员
        if (!isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限更新用户状态");
        }

        // 查找用户
        User userToUpdate = userMapper.selectById(userId);
        if (userToUpdate == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        // 更新用户状态
        return userMapper.updateStatus(userId, status) > 0;
    }

    @Override
    public boolean deleteUser(long userId, User loginUser) {
        // 检查是否为管理员
        if (!isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限删除用户");
        }

        // 查找用户
        User userToDelete = userMapper.selectById(userId);
        if (userToDelete == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        }

        // 删除用户
        return userMapper.deleteById(userId) > 0;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue() == user.getRole();
    }
    
    @Override
    public int countUsers() {
        return userMapper.countAll();
    }
}